﻿/// <reference path="../plugins/jquery/jquery.js" />
/// <reference path="../plugins/layer/layer.js" />

/*
 * @author Aaron
 */

!function ($) {
    "use strict";
    //defalut setting
    $.ajaxSetup({
        cache: false
    });

    var jqFn = {

        disable: function () {
            this.each(function () {
                $(this).attr("disabled", "disabled");
            });
            return this;
        },
        enable: function () {
            this.each(function () {
                $(this).removeAttr("disabled");
            });
            return this;
        },
        fillOptions: function (_scource, _textCol, _valCol, _withEmptyOption) {
            this.each(function () {
                var obj = $(this);
                obj.empty();
                if (_withEmptyOption === true) {
                    var option = $("<Option />");
                    obj.append(option);
                    option.text("--请选择--");
                    option.val("");
                }

                $.each(_scource || [], function (m, n) {
                    var option = $("<Option />");
                    obj.append(option);
                    option.text(n[_textCol || "text"]);
                    option.val(n[_valCol || "value"]);
                    option.data("SourceData", n);
                });
            });
            return this;
        }
    };
    jQuery.extend($.fn, jqFn);
}(jQuery);


!function ($) {
    "use strict";
    var handle = {
        /*日期字符串格式化为需要的，2014-05-06T12:30:45.456 -> 2014-05-06*/
        formatDateString: function (strDate) {
            if (!strDate || strDate.substring(0, 4) === "0001") return "";
            return strDate.substring(0, 10);
            //return new Date(strDate.replace(/-/g, "/")).toLocaleDateString();
        },
        log: function () {
            if (typeof console === "object") {
                for (var i = 0; i < arguments.length; i++) {
                    console.log(arguments[i]);
                }
            }
        },
        loading: function () {
            layer.load();
        },
        closeLoading: function () {
            layer.closeAll('loading');
        },
        equalizeHeights: function () {
            var heights = this.map(function (i, e) {
                return $(e).height();
            }).get();
            return this.height(Math.max.apply(this, heights));
        },
        open: function (url, _config) {
            var _defalutConfig = {
                width: 872,
                height: window.screen.height,
                left: Math.round((window.screen.width - 870) / 2),
                top: 0
            };
            $.extend(_defalutConfig, _config);
            var page = null;
            if (!_config)
                page = window.open(url);
            else
                page = window.open(url, _defalutConfig.name || "", "width=" + _defalutConfig.width + "px,height=" + _defalutConfig.height + "px, top=" + _defalutConfig.top + ", left= " + _defalutConfig.left + ", toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no");
            return page;
        },
        alert: function (msg, callback) {
            layer.alert(msg, callback);
            this.closeLoading();
        },

        confirm: function (msg, func, funcNo) {
            layer.confirm(msg, func, funcNo);
        },
        confirmNotice: function (msg, func, funcNo) {
            //$("body").append("<div  style='display: none' id='dialog-confirm-Notice' title='通知消息'><p><span class='ui-icon ui-icon-circle-check' style='float:left; margin:0 7px 50px 0;'></span>" + msg + "</p></div>");
            var dialog = $("#dialog-message");
            dialog.prop("title", "通知消息");
            dialog.find("label").text(msg);
            dialog.dialog({
                modal: true,
                width: 350,
                height: 250,
                buttons: {
                    '查看单据': function () {
                        $(this).dialog("close");
                        if (func) func();
                    },
                    '关闭': function () { $(this).dialog("close"); if (funcNo) funcNo(); }
                },
                close: function (event, ui) {
                    if (event.eventPhase === 2 && funcNo)
                        funcNo();
                }
            });
        },
        startWith: function (s, b) {
            if (s === null || s === "" || b.length === 0 || s.length > b.length)
                return false;
            if (b.substr(0, s.length) === s)
                return true;
            else
                return false;
        },
        parseURL: function (url) {
            var a = document.createElement('a');
            a.href = url;
            return {
                source: url,
                protocol: a.protocol.replace(':', ''),
                host: a.hostname,
                port: a.port,
                query: a.search,
                params: (function () {
                    var ret = {},
                        seg = a.search.replace(/^\?/, '').split('&'),
                        len = seg.length, i = 0, s;
                    for (; i < len; i++) {
                        if (!seg[i]) { continue; }
                        s = seg[i].split('=');
                        ret[s[0]] = s[1];
                    }
                    return ret;
                })(),
                file: (a.pathname.match(/\/([^\/?#]+)$/i) || [''])[1],
                hash: a.hash.replace('#', ''),
                path: a.pathname.replace(/^([^\/])/, '/$1'),
                relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [''])[1],
                segments: a.pathname.replace(/^\//, '').split('/')
            };
        },
        urlParam: function () {
            var url = window.location.href;
            var obj = $.parseURL(url);
            return obj.params || {};
        },
        substring: function (strOld, length, replacement) {
            var s = $.trim(strOld);
            if (s.length === 0) return s;
            if (s.length > length) {
                s = s.substring(0, length - 1);
            }
            if (replacement) {
                s += replacement;
            }
            return s;
        },
        sPost: function (url, param, funcSuccess, funcError, isAsync) {
            $.ajax({
                async: isAsync === false ? false : true,
                type: "post",
                dataType: 'json',
                xhrFields: { withCredentials: true },
                url: url,
                data: param,
                success: function (box) {
                    if (!box.result) {
                        if ($.isFunction(funcError)) {
                            funcError();
                        } else
                            $.alert(box.message);
                    }
                    else {
                        funcSuccess(box);

                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (XMLHttpRequest.status === 401 || XMLHttpRequest.status === 0) {
                        window.location = "/account/login";
                    }
                    else if ($.isFunction(funcError)) {
                        funcError();

                    } else {
                        $.alert("请重新登陆！", function () {  window.location = "/account/login"; });
                    }

                }
            });
        },
        sGet: function (url, param, funcSuccess, funcError, isAsync) {
            $.ajax({
                async: isAsync === false ? false : true,
                type: "get",
                datatype: "json",
                xhrFields: { withCredentials: true },
                url: url,
                data: param,
                success: function (box) {
                    if (!box.result) {
                       if ($.isFunction(funcError)) {
                            funcError();
                        } else
                            $.alert(box.Message);
                    }
                    else {
                        funcSuccess(box);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (XMLHttpRequest.status === 401 || XMLHttpRequest.status === 0) {
                        window.location = "account/login";
                    }
                    else if ($.isFunction(funcError)) {
                        funcError();

                    } else {
                        $.alert("服务异常！");
                    }

                }
            });
        }

    };

    jQuery.extend($, handle);
    $.substr = $.substring;
}(jQuery);

!function () {
    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length === 1 && typeof (args) === "object") {
                for (var key in args) {
                    if (args[key] !== undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] !== undefined) {
                        var reg2 = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg2, arguments[i]);
                    }
                }
            }
        }
        return result;
    },
        Date.prototype.format = function (format) {
            var o = {
                "M+": this.getMonth() + 1, //month
                "d+": this.getDate(),    //day
                "h+": this.getHours(),   //hour
                "m+": this.getMinutes(), //minute
                "s+": this.getSeconds(), //second
                "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
                "S": this.getMilliseconds() //millisecond
            };
            if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o) if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length === 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
            return format;
        };
}();